//
//  MyInformationViewController.m
//  InviteJob
//
//  Created by LangLang on 17/10/31.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "MyInformationViewController.h"
#import "TZImagePickerController.h"

@interface MyInformationViewController ()<TZImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *headerImage;

@property (weak, nonatomic) IBOutlet UITextField *userName;

@property (weak, nonatomic) IBOutlet UITextField *recommendPhone;

@property (nonatomic, strong) UIButton *navRightButton;

@property (nonatomic, strong) TZImagePickerController *imagePicker;

@property (nonatomic, strong) NSArray *arrHeaderImage;

@end

@implementation MyInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = strColor(@"f6f6f6");
    TitleView(@"个人信息")
    
    isUser
    
    
     [_headerImage sd_setImageWithURL:[NSURL URLWithString:user.avatar] placeholderImage:[UIImage imageNamed:@"img_default_head"]];
    if (user.user_name.length>0) {
        _userName.text = user.user_name;
    }
    if (user.p_phone.length>0) {
        _recommendPhone.text = user.p_phone;
        _recommendPhone.userInteractionEnabled = NO;
    }
    
    _headerImage.layer.masksToBounds = YES;
    _headerImage.clipsToBounds = YES;
    _headerImage.layer.cornerRadius = 40;
    [_headerImage setUserInteractionEnabled:YES];
    [_headerImage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];
    // right item
    self.navRightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [self.navRightButton setTitle:@"保存" forState:UIControlStateNormal];
    self.navRightButton.titleEdgeInsets = UIEdgeInsetsMake(0,10, 0, -10);
    self.navRightButton.titleLabel.font = [UIFont systemFontOfSize:16];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.navRightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    [self.navRightButton addTarget:self action:@selector(navSaveAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}
-(void)clickCategory:(UITapGestureRecognizer *)gestureRecognizer{
    [self configImageSelector];
}

#pragma mark - 选择图片
- (void)configImageSelector {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto){
        _arrHeaderImage = photos;
        _headerImage.image = photos[0];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}

-(void)navSaveAction{
    
    if (_userName.text.length==0) {
        SHuiMBhudTextTimeStr(@"姓名不能为空");
        return;
    }
    
    NSString *strUrl = [NSString stringWithFormat:post_modifyUserInfo_api];
    
    isUser
    NSDictionary *parameter = @{@"user_id":user.user_id,
                                @"token":user.token,
                                @"p_phone":_recommendPhone.text,
                                @"user_name":_userName.text};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/javascript",nil];
    manager.requestSerializer.timeoutInterval = 10;
     [MBProgressHUD showMessag:@"保存中..." withDelay:0 toView:self. view withMode:MBProgressHUDModeIndeterminate hideWithDelay:0];
    [manager POST:strUrl parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (_arrHeaderImage.count!=0) {
            NSData *imageData = [self compressOriginalImage:_arrHeaderImage[0] toMaxDataSizeKBytes:200];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
            [formData appendPartWithFileData:imageData
                                        name:@"header"
                                    fileName:fileName
                                    mimeType:@"image/png"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
       
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",data);
        SHuiMBHidleYes
        if ([data[@"code"] intValue] == 200) {
            SHuiMBhudTextTimeStr(@"保存成功");
            // 更新后存储用户信息
            [UserModel responseObject:data];
            
        }else{
            SHuiMBhudTextTimeStr(data[@"mark"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        SHuiMBHidleYes
        SHuiMBhudTextTimeStr(@"网络异常");
    }];
    
}

//图片压缩到指定大小
/**
 *  压缩图片到指定文件大小
 *
 *  @param image 目标图片
 *  @param size  目标大小（最大值）
 *
 *  @return 返回的图片文件
 */
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}

@end
